using System.Collections.Generic;
using System.Linq;

namespace HyuFrameWork
{
    public class UIPage : UIPanel
    {
        public UIPageChild[] Children => GetComponentsInChildren<UIPageChild>(true);

        public IEnumerable<UIWindow> ChildrenWindows => Children.Where(o => o is UIWindow).Cast<UIWindow>();
        public IEnumerable<UIWidget> ChildrenWidgets => Children.Where(o => o is UIWidget).Cast<UIWidget>();

        public override void Open()
        {
            base.Open();
            var lastPage = UIManager.Instance.CurrentPage;
            if (lastPage) lastPage.gameObject.SetActive(false);
            
            UIManager.Instance.PageStack.Add(this);
        }

        public override void Close()
        {
            if (UIManager.Instance.PageStack.Count <= 1) return;

            foreach (var child in Children)
            {
                if(child) child.Close();
            }
            
            base.Close();
            UIManager.Instance.PageStack.Remove(this);
            
            var lastPage = UIManager.Instance.CurrentPage;
            if(lastPage) lastPage.gameObject.SetActive(true);
        }
    }
}